<template>
  <div
    v-show="isVisiable"
    :class="`multi-params ${componentStyle}-Style`"
  >
    <el-icon
      class="flag_icon"
      :style="getCssStyle('icon')"
      @click="openDialog()"
    >
      <Operation />
    </el-icon>
    <el-dialog
      v-model="dialogVisible"
      :title="$demoi18n('multi-params.publicParameterEditing')"
      width="320px"
      append-to-body
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :class="`visualComponents_theme_${componentStyle} ${componentStyle}-Style ${xvueNameSpace}`"
      @close="canelDialog()"
    >
      <table :class="`params_list visualComponents_theme_${componentStyle} ${componentStyle}-Style`">
        <tr>
          <th
            class="th_param_name"
            :title="$demoi18n('multi-params.parameterName')"
          >{{
            $demoi18n('multi-params.parameterName')
          }}</th>
          <th style="width:200px;" :title="$demoi18n('multi-params.parameterValue')">{{ $demoi18n('multi-params.parameterValue') }}</th>
        </tr>
        <tr
          v-for="(param, i) in params_"
          :key="i"
        >
          <td>
            <div
              class="desc"
              :title="param.desc"
            >{{ param.desc }}</div>
          </td>
          <td>
            <ValueInputer
              v-model:value="param.value"
              :componentStyle="componentStyle"
              :value-type="getValueType(param.valueType)"
              :enum-values="getEnumValues(param.optionValues)"
              base-ruled
            />
          </td>
        </tr>
      </table>

      <template #footer>
        <span>
          <el-button
            size="small"
            @click="reset()"
          >{{ $demoi18n('btn.reset') }}</el-button>
          <el-button
            size="small"
            @click="canelDialog()"
          >{{ $demoi18n('btn.cancel') }}</el-button>
          <el-button
            type="primary"
            size="small"
            @click="saveDialog()"
          >
            {{ $demoi18n('btn.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import chartBase from '@/mixin/chart-base.js';
import storage from '@/storage/storage.js';
import { visualAction } from '@/utils/util';
import { mapMutations, mapState } from 'vuex';
import config from './config/config.js';
import dfCssStyle from './config/cssStyle-default.js';

export default {
  components: { ValueInputer },
  mixins: [chartBase],
  props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h', 'isDesignView'],
  data() {
    const _config = JSON.parse(JSON.stringify(config));
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      ...config.config.property,
      orgConfig: null,
      ignoreBaseEmitComponentStatus: true, // 忽略base文件中watch的emitComponentStatus
      dialogVisible: false,
      dfCssStyle,
      params_: [],
    };
  },
  computed: {
    ...mapState({
      commonParams: state => state.VisualComponentsModule.commonParams,
    }),
    isVisiable() {
      let visible;
      if (this.isDesignView || this.$route.name === 'PageOrchestration' || window.isLocalEnv) {
        visible = true;
      } else {
        // 非编辑态
        visible = this.isPreviewVisible;
      }
      return visible;
    },
  },
  watch: {},
  created() {
    this.orgConfig = config;
    this.config = JSON.parse(JSON.stringify(this.orgConfig));
    this.setCompStatus(true);
  },
  beforeUnmount() {
    this.delCommonParams(this.widgetInstanceId);
  },
  methods: {
    ...mapMutations(['setComponentStatus', 'setCommonParams', 'delCommonParams']),
    setCompStatus(hasAsync) {
      this.setComponentStatus({
        pageId: this.pageId,
        widgetInstanceId: this.widgetInstanceId,
        hasAsync,
      });
    },
    async loadWidget() {
      this.updateConfigProperty();
      await this.loadFromStore();
      this._setCommonParams();
      this.afterLoadWidget();
    },
    _setCommonParams() {
      const { events } = this.config;
      this.setCommonParams({
        widgetInstanceId: this.widgetInstanceId,
        evtKey: events[0].key,
        params: JSON.parse(JSON.stringify(this.params)),
      });
      this.setCompStatus(false);
    },
    getValueType(type) {
      const map = {
        string: 'String',
        date: 'Date',
        number: 'Number',
      };
      return map[type];
    },
    getEnumValues(options) {
      let arr = [];
      if (options) {
        arr = options.map(n => {
          const label = n.value === n.desc ? n.desc : `${n.value} (${n.desc})`;
          return {
            label,
            value: n.value,
          };
        });
      }
      return arr;
    },
    openDialog() {
      this.params_ = JSON.parse(JSON.stringify(this.params));
      this.dialogVisible = true;
    },
    canelDialog() {
      this.dialogVisible = false;
    },
    saveDialog() {
      this.dialogVisible = false;
      this.params = JSON.parse(JSON.stringify(this.params_));
      this._setCommonParams();
      storage.setItem('commonParams', JSON.stringify(this.commonParams));
      this.executeAction();
    },
    reset() {
      this.params_ = JSON.parse(JSON.stringify(this.config.config.property.params));
    },
    async loadFromStore() {
      const action = visualAction();
      if (action !== 'saveAllData' && this.isKeepCache !== false) {
        const indexedDBcommonParams = await storage.getItem('commonParams') || '{}';
        const commonParams = (JSON.parse(indexedDBcommonParams)) || {};
        const cache = commonParams[this.widgetInstanceId];
        if (cache) {
          this.params = cache.params;
        }
      }
      return true;
    },
  },
};
</script>
<style lang="less" scoped>
@import './config/theme.less';
.multi-params {
  .flag_icon {
    cursor: pointer;
  }
}
.params_list {
  border-collapse: collapse;
  th,
  td {
    padding: 5px 10px;
  }
  th {
    text-align: left;
    &.th_param_name {
      text-align: right;
      text-overflow: ellipsis;
      overflow: hidden;
      max-width: 120px;
      white-space: nowrap;
    }
  }
  td {
    .desc {
      text-align: right;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 28px;
      max-width: 120px;
      white-space: nowrap;
      line-height: 28px;
      // color: #939393;
      color: var(--desc-color);
    }
    :deep(.el-input-number .el-input__inner) {
      text-align: left;
    }
  }
}

// .visualComponents_theme_light {
//   td {
//     background-color: #fff;
//   }
// }

// .visualComponents_theme_dark {

// }
</style>
